using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using SqlSugar;
using CaipuGuanliXitong.Models;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;

namespace CaipuGuanliXitong.Controllers;

public class RecipeIngredientController : Controller
{
    private readonly CookBookDbContext _context;

    public RecipeIngredientController(CookBookDbContext context)
    {
        _context = context;
    }

    // GET: RecipeIngredient
    public async Task<IActionResult> Index(string searchString, string sortOrder, int page = 1)
    {
        const int pageSize = 10;
        
        ViewBag.CurrentSort = sortOrder;
        ViewBag.CookBookNameSortParm = sortOrder == "CookBookName" ? "cookbookname_desc" : "CookBookName";
        ViewBag.IngredientNameSortParm = sortOrder == "IngredientName" ? "ingredientname_desc" : "IngredientName";
        ViewBag.QuantitySortParm = sortOrder == "Quantity" ? "quantity_desc" : "Quantity";
        ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
        
        var query = _context.RecipeIngredients.AsQueryable().Where(x => !x.IsDeleted);
        
        if (!String.IsNullOrEmpty(searchString))
        {
            query = query.Where(s => s.CookBookName.Contains(searchString) || s.IngredientName.Contains(searchString));
            ViewBag.CurrentFilter = searchString;
        }
        
        switch (sortOrder)
        {
            case "cookbookname_desc":
                query = query.OrderByDescending(x => x.CookBookName);
                break;
            case "CookBookName":
                query = query.OrderBy(x => x.CookBookName);
                break;
            case "ingredientname_desc":
                query = query.OrderByDescending(x => x.IngredientName);
                break;
            case "IngredientName":
                query = query.OrderBy(x => x.IngredientName);
                break;
            case "quantity_desc":
                query = query.OrderByDescending(x => x.Quantity);
                break;
            case "Quantity":
                query = query.OrderBy(x => x.Quantity);
                break;
            case "Date":
                query = query.OrderBy(x => x.CreatedTime);
                break;
            case "date_desc":
                query = query.OrderByDescending(x => x.CreatedTime);
                break;
            default:
                query = query.OrderBy(x => x.Id);
                break;
        }
        
        var totalItems = await query.CountAsync();
        var recipeIngredients = await query.ToPageListAsync(page, pageSize);
        
        ViewBag.TotalItems = (int)totalItems;
        ViewBag.CurrentPage = page;
        ViewBag.PageSize = pageSize;
        
        return View(recipeIngredients);
    }

    // GET: RecipeIngredient/Details/5
    public IActionResult Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var recipeIngredient = _context.RecipeIngredients.AsQueryable().Where(x => !x.IsDeleted).First(x => x.Id == id.Value);
        if (recipeIngredient == null)
        {
            return NotFound();
        }

        return View(recipeIngredient);
    }

    // GET: RecipeIngredient/Create
    public IActionResult Create(string cookBookSearch = "")
    {
        // 获取所有菜谱
        var allCookBooks = _context.CookBooks.GetList().Where(x => !x.IsDeleted).ToList();
        
        // 如果有搜索条件，则筛选菜谱
        if (!string.IsNullOrEmpty(cookBookSearch))
        {
            ViewBag.CookBooks = allCookBooks.Where(c => c.Name.Contains(cookBookSearch)).ToList();
        }
        else
        {
            ViewBag.CookBooks = allCookBooks.Take(20).ToList(); // 默认只显示前20个菜谱
        }
        
        // 对于食材，初始时不加载任何数据，需要用户搜索
        ViewBag.Ingredients = new List<Ingredient>(); 
        ViewBag.CookBookSearch = cookBookSearch;
        return View();
    }

    // POST: RecipeIngredient/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create([Bind("CookBookId,IngredientId,Quantity")] RecipeIngredient recipeIngredient)
    {
        if (ModelState.IsValid)
        {
            try
            {
                // 获取菜谱和食材信息
                var cookBook = _context.CookBooks.AsQueryable().Where(x => !x.IsDeleted).First(x => x.Id == recipeIngredient.CookBookId);
                var ingredient = _context.Ingredients.AsQueryable().Where(x => !x.IsDeleted).First(x => x.Id == recipeIngredient.IngredientId);
                
                recipeIngredient.CookBookName = cookBook.Name;
                recipeIngredient.IngredientName = ingredient.Name;
                recipeIngredient.CreatedTime = DateTime.Now;
                recipeIngredient.UpdatedTime = DateTime.Now;
                recipeIngredient.Price = ingredient.Price * recipeIngredient.Quantity;
                
                _context.RecipeIngredients.Insert(recipeIngredient);
                ViewBag.Message = "带量食材创建成功";
                ViewBag.IsSuccess = true;
                return RedirectToAction(nameof(Index));
            }
            catch (Exception ex)
            {
                ViewBag.Message = "创建失败: " + ex.Message;
                ViewBag.IsSuccess = false;
            }
        }
        
        ViewBag.CookBooks = _context.CookBooks.GetList().Where(x => !x.IsDeleted).ToList();
        ViewBag.Ingredients = _context.Ingredients.GetList().Where(x => !x.IsDeleted).ToList();
        return View(recipeIngredient);
    }

    // GET: RecipeIngredient/Edit/5
    public IActionResult Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var recipeIngredient = _context.RecipeIngredients.AsQueryable().Where(x => !x.IsDeleted).First(x => x.Id == id.Value);
        if (recipeIngredient == null)
        {
            return NotFound();
        }
        
        // 获取所有菜谱和食材
        var allCookBooks = _context.CookBooks.GetList().Where(x => !x.IsDeleted).ToList();
        var allIngredients = _context.Ingredients.GetList().Where(x => !x.IsDeleted).ToList();
        
        ViewBag.CookBooks = allCookBooks.Take(20).ToList(); // 默认显示前20个菜谱
        ViewBag.Ingredients = allIngredients;
        return View(recipeIngredient);
    }

    // POST: RecipeIngredient/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Edit(int id, [Bind("Id,CookBookId,IngredientId,Quantity,CreatedTime")] RecipeIngredient recipeIngredient)
    {
        if (id != recipeIngredient.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                var cookBook = _context.CookBooks.AsQueryable().Where(x => !x.IsDeleted).First(x => x.Id == recipeIngredient.CookBookId);
                var ingredient = _context.Ingredients.AsQueryable().Where(x => !x.IsDeleted).First(x => x.Id == recipeIngredient.IngredientId);
                
                recipeIngredient.CookBookName = cookBook.Name;
                recipeIngredient.IngredientName = ingredient.Name;
                recipeIngredient.UpdatedTime = DateTime.Now;
                recipeIngredient.Price = ingredient.Price * recipeIngredient.Quantity;
                
                _context.RecipeIngredients.Update(recipeIngredient);
                ViewBag.Message = "带量食材更新成功";
                ViewBag.IsSuccess = true;
                return RedirectToAction(nameof(Index));
            }
            catch (Exception ex)
            {
                ViewBag.Message = "更新失败: " + ex.Message;
                ViewBag.IsSuccess = false;
            }
        }
        
        ViewBag.CookBooks = _context.CookBooks.GetList().Where(x => !x.IsDeleted).ToList();
        ViewBag.Ingredients = _context.Ingredients.GetList().Where(x => !x.IsDeleted).ToList();
        return View(recipeIngredient);
    }

    // GET: RecipeIngredient/Delete/5
    public IActionResult Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var recipeIngredient = _context.RecipeIngredients.AsQueryable().Where(x => !x.IsDeleted).First(x => x.Id == id.Value);
        if (recipeIngredient == null)
        {
            return NotFound();
        }

        return View(recipeIngredient);
    }

    // POST: RecipeIngredient/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public IActionResult DeleteConfirmed(int id)
    {
        var recipeIngredient = _context.RecipeIngredients.AsQueryable().First(x => x.Id == id);
        recipeIngredient.IsDeleted = true;
        recipeIngredient.UpdatedTime = DateTime.Now;
        _context.RecipeIngredients.Update(recipeIngredient);
        return RedirectToAction(nameof(Index));
    }
    
    // GET: RecipeIngredient/Export
    public IActionResult ExportToExcel()
    {
        var recipeIngredients = _context.RecipeIngredients.GetList();
        
        // 创建工作簿
        var workbook = new XSSFWorkbook();
        var sheet = workbook.CreateSheet("带量食材数据");
        
        // 创建表头
        var headerRow = sheet.CreateRow(0);
        headerRow.CreateCell(0).SetCellValue("编号");
        headerRow.CreateCell(1).SetCellValue("菜谱编号");
        headerRow.CreateCell(2).SetCellValue("菜谱名称");
        headerRow.CreateCell(3).SetCellValue("食材编号");
        headerRow.CreateCell(4).SetCellValue("食材名称");
        headerRow.CreateCell(5).SetCellValue("用量");
        headerRow.CreateCell(6).SetCellValue("价格");
        headerRow.CreateCell(7).SetCellValue("创建时间");
        headerRow.CreateCell(8).SetCellValue("修改时间");
        
        // 填充数据
        for (int i = 0; i < recipeIngredients.Count; i++)
        {
            var row = sheet.CreateRow(i + 1);
            var recipeIngredient = recipeIngredients[i];
            row.CreateCell(0).SetCellValue(recipeIngredient.Id);
            row.CreateCell(1).SetCellValue(recipeIngredient.CookBookId);
            row.CreateCell(2).SetCellValue(recipeIngredient.CookBookName);
            row.CreateCell(3).SetCellValue(recipeIngredient.IngredientId);
            row.CreateCell(4).SetCellValue(recipeIngredient.IngredientName);
            row.CreateCell(5).SetCellValue((double)recipeIngredient.Quantity);
            row.CreateCell(6).SetCellValue((double)recipeIngredient.Price);
            row.CreateCell(7).SetCellValue(recipeIngredient.CreatedTime.ToString("yyyy-MM-dd HH:mm:ss"));
            row.CreateCell(8).SetCellValue(recipeIngredient.UpdatedTime.ToString("yyyy-MM-dd HH:mm:ss"));
        }
        
        // 调整列宽
        for (int i = 0; i < 9; i++)
        {
            sheet.AutoSizeColumn(i);
        }
        
        // 写入内存流
        var memoryStream = new MemoryStream();
        workbook.Write(memoryStream, true);
        memoryStream.Position = 0;
        
        return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "带量食材数据.xlsx");
    }
    
    // POST: RecipeIngredient/Import
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult ImportFromExcel(IFormFile file)
    {
        if (file == null || file.Length == 0)
        {
            ViewBag.Message = "请选择一个文件";
            ViewBag.IsSuccess = false;
            return View("Index", _context.RecipeIngredients.GetList());
        }
        
        try
        {
            var importedCount = 0;
            
            using (var stream = file.OpenReadStream())
            {
                var workbook = new XSSFWorkbook(stream);
                var sheet = workbook.GetSheetAt(0);
                
                // 从第二行开始读取数据（跳过表头）
                for (int row = 1; row <= sheet.LastRowNum; row++)
                {
                    var dataRow = sheet.GetRow(row);
                    if (dataRow == null) continue;
                    
                    // 确保行有足够数据
                    if (dataRow.Cells.Count < 9) continue;
                    
                    // 读取数据
                    var idCell = dataRow.GetCell(0);
                    var cookBookIdCell = dataRow.GetCell(1);
                    var cookBookNameCell = dataRow.GetCell(2);
                    var ingredientIdCell = dataRow.GetCell(3);
                    var ingredientNameCell = dataRow.GetCell(4);
                    var quantityCell = dataRow.GetCell(5);
                    var priceCell = dataRow.GetCell(6);
                    var createdTimeCell = dataRow.GetCell(7);
                    var updatedTimeCell = dataRow.GetCell(8);
                    
                    if (idCell == null || cookBookIdCell == null || cookBookNameCell == null || 
                        ingredientIdCell == null || ingredientNameCell == null || quantityCell == null || priceCell == null) continue;
                    
                    var id = (int)idCell.NumericCellValue;
                    var cookBookId = (int)cookBookIdCell.NumericCellValue;
                    var cookBookName = cookBookNameCell.ToString();
                    var ingredientId = (int)ingredientIdCell.NumericCellValue;
                    var ingredientName = ingredientNameCell.ToString();
                    var quantity = quantityCell.NumericCellValue;
                    var price = priceCell.NumericCellValue;
                    
                    // 解析时间
                    DateTime createdTime = DateTime.Now;
                    DateTime updatedTime = DateTime.Now;
                    
                    if (createdTimeCell != null)
                    {
                        if (createdTimeCell.CellType == CellType.Numeric)
                        {
                            var dateValue = createdTimeCell.DateCellValue;
                            if (dateValue.HasValue)
                            {
                                createdTime = dateValue.Value;
                            }
                        }
                        else if (createdTimeCell.CellType == CellType.String)
                        {
                            DateTime parsedCreatedTime;
                            if (DateTime.TryParse(createdTimeCell.StringCellValue, out parsedCreatedTime))
                            {
                                createdTime = parsedCreatedTime;
                            }
                        }
                    }
                    
                    if (updatedTimeCell != null)
                    {
                        if (updatedTimeCell.CellType == CellType.Numeric)
                        {
                            var dateValue = updatedTimeCell.DateCellValue;
                            if (dateValue.HasValue)
                            {
                                updatedTime = dateValue.Value;
                            }
                        }
                        else if (updatedTimeCell.CellType == CellType.String)
                        {
                            DateTime parsedUpdatedTime;
                            if (DateTime.TryParse(updatedTimeCell.StringCellValue, out parsedUpdatedTime))
                            {
                                updatedTime = parsedUpdatedTime;
                            }
                        }
                    }
                    
                    // 检查是否存在相同ID的带量食材
                    var existingRecipeIngredient = _context.RecipeIngredients.AsQueryable()
                        .Any(x => x.Id == id);
                    
                    if (existingRecipeIngredient)
                    {
                        // 更新现有带量食材
                        var recipeIngredient = _context.RecipeIngredients.AsQueryable()
                            .First(x => x.Id == id);
                        recipeIngredient.CookBookId = cookBookId;
                        recipeIngredient.CookBookName = cookBookName ?? "";
                        recipeIngredient.IngredientId = ingredientId;
                        recipeIngredient.IngredientName = ingredientName ?? "";
                        recipeIngredient.Quantity = (decimal)quantity;
                        recipeIngredient.Price = (decimal)price;
                        recipeIngredient.UpdatedTime = updatedTime;
                        _context.RecipeIngredients.Update(recipeIngredient);
                    }
                    else
                    {
                        // 创建新带量食材
                        var recipeIngredient = new RecipeIngredient
                        {
                            Id = id,
                            CookBookId = cookBookId,
                            CookBookName = cookBookName ?? "",
                            IngredientId = ingredientId,
                            IngredientName = ingredientName ?? "",
                            Quantity = (decimal)quantity,
                            Price = (decimal)price,
                            CreatedTime = createdTime,
                            UpdatedTime = updatedTime
                        };
                        _context.RecipeIngredients.Insert(recipeIngredient);
                    }
                    
                    importedCount++;
                }
            }
            
            ViewBag.Message = $"成功导入 {importedCount} 条带量食材数据";
            ViewBag.IsSuccess = true;
        }
        catch (Exception ex)
        {
            ViewBag.Message = "导入失败: " + ex.Message;
            ViewBag.IsSuccess = false;
        }
        
        var recipeIngredients = _context.RecipeIngredients.GetList();
        return View("Index", recipeIngredients);
    }
    
    // GET: RecipeIngredient/SearchCookBooks
    [HttpGet]
    public JsonResult SearchCookBooks(string term)
    {
        if (string.IsNullOrEmpty(term))
        {
            return Json(new List<object>());
        }
        
        var cookBooks = _context.CookBooks.AsQueryable()
            .Where(c => c.Name.Contains(term))
            .Select(c => new { 
                id = c.Id, 
                text = c.Name 
            })
            .ToList();
        
        return Json(cookBooks);
    }
    
    // GET: RecipeIngredient/SearchIngredients
    [HttpGet]
    public JsonResult SearchIngredients(string term)
    {
        if (string.IsNullOrEmpty(term))
        {
            return Json(new List<object>());
        }
        
        var ingredients = _context.Ingredients.AsQueryable()
            .Where(i => i.Name.Contains(term))
            .Select(i => new { 
                id = i.Id, 
                text = i.Name 
            })
            .ToList();
        
        return Json(ingredients);
    }
    
    // GET: RecipeIngredient/CreateMultiple
    public IActionResult CreateMultiple()
    {
        ViewBag.CookBooks = _context.CookBooks.GetList().Take(20).ToList();
        return View();
    }
    
    // POST: RecipeIngredient/CreateMultiple
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult CreateMultiple(RecipeIngredientDto model)
    {
        // 手动验证食材列表
        if (model.Ingredients == null || model.Ingredients.Count == 0)
        {
            ModelState.AddModelError("", "请至少添加一个食材");
        }
        else
        {
            for (int i = 0; i < model.Ingredients.Count; i++)
            {
                if (model.Ingredients[i].IngredientId <= 0)
                {
                    ModelState.AddModelError("", "请选择所有食材");
                    break;
                }
                
                if (model.Ingredients[i].Quantity <= 0)
                {
                    ModelState.AddModelError("", "所有食材的用量必须大于0");
                    break;
                }
            }
        }
        
        if (ModelState.IsValid)
        {
            try
            {
                var cookBook = _context.CookBooks.AsQueryable().First(x => x.Id == model.CookBookId);
                var createdCount = 0;
                
                foreach (var ingredientSelection in model.Ingredients)
                {
                    if (ingredientSelection.IngredientId > 0 && ingredientSelection.Quantity > 0)
                    {
                        var ingredient = _context.Ingredients.AsQueryable()
                            .First(x => x.Id == ingredientSelection.IngredientId);
                        
                        var recipeIngredient = new RecipeIngredient
                        {
                            CookBookId = model.CookBookId,
                            CookBookName = cookBook.Name,
                            IngredientId = ingredient.Id,
                            IngredientName = ingredient.Name,
                            Quantity = ingredientSelection.Quantity,
                            Price = ingredient.Price * ingredientSelection.Quantity,
                            CreatedTime = DateTime.Now,
                            UpdatedTime = DateTime.Now
                        };
                        
                        _context.RecipeIngredients.Insert(recipeIngredient);
                        createdCount++;
                    }
                }
                
                ViewBag.Message = $"成功为菜谱'{cookBook.Name}'创建了{createdCount}个带量食材";
                ViewBag.IsSuccess = true;
                return RedirectToAction(nameof(Index));
            }
            catch (Exception ex)
            {
                ViewBag.Message = "创建失败: " + ex.Message;
                ViewBag.IsSuccess = false;
            }
        }
        
        ViewBag.CookBooks = _context.CookBooks.GetList();
        return View(model);
    }
}